package com.example.uCenter.user.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/upload")
public class UpLoadController {

    @PostMapping("/file")
    public String uploadFile(@RequestParam("pic") MultipartFile mf) throws IOException {
        // 1、获取原文件名(含后缀)
        String fileName = mf.getOriginalFilename();  // 文件原名
        // 2、取后缀名
        int i = fileName.lastIndexOf(".");
        String sufx = fileName.substring(i);
        System.out.println("sufx = " + sufx);
        // 3、自动生成前缀名
        fileName = UUID.randomUUID().toString() + sufx;

        File newFile = new File("C:/Users/18061/Desktop/upload");
        if (!newFile.exists()) {
            System.out.println("1111111111111111");
            newFile.mkdir();
        }
        // 4、将文件拷贝至服务器
        mf.transferTo(new File(newFile, fileName));
        System.out.println("文件上传成功");

        // 5、插入数据库(文件路径和文件名)

        return "OK";
    }
}
